const http = require('http')
const url = require('url')
const qs = require('querystring')
const path = require('path')
const fs = require('fs')

http.createServer((req, res) => {
  let method = req.method.toLowerCase()
  let headers = req.headers
  let url = req.url
  let baseName = path.basename(req.url)
  console.log(`baseName: ${baseName}`)
  let extName = path.extname(baseName)
  console.log(`extName: ${extName}`)
  let root = './'
  let types = {
    '.css': 'text/css',
    '.js': 'application/javascript',
    '.ico': 'image/icon'
  }
  if (method === 'get') {
    if (extName) {
      if (fs.existsSync(root + baseName)) {
        fs.readFile(root + baseName, 'utf8', (err, data) => {
          if (err) throw err
          res.writeHead(200, {
            'Content-Type': types[extName]
          })
          res.write(data)
          res.end()
        })
      } else {
        console.log('file: ' + root + baseName + ' is not exist!')
      }
    } else {
      fs.readFile(root + 'index.html', 'utf8', (err, data) => {
        if (err) throw err
        res.writeHead(200, {'Content-Type': 'text/html'})
        res.write(data)
        res.end()
      })
    }
  } else if (method === 'post') {
    let body = []
    req.on('data', chunk => {
      body.push(chunk)
    }).on('end', () => {
      console.log(`body: ${body}`)
      body = qs.parse(Buffer.concat(body).toString())
      res.statusCode = 200
      res.setHeader('Content-Type', 'application/json')
      let output = { url, headers, body, method }
      res.end(JSON.stringify(output, null, 2))
    })
  }
}).listen(3000)

console.log('server running at http://localhost:3000/')
